package com.qiaoanju.back.service.impl.system;

import com.qiaoanju.back.dao.system.IMenuDao;
import com.qiaoanju.back.domain.system.MenuModel;
import com.qiaoanju.back.service.system.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by eversec on 2017/9/21.
 */
@Service
public class MenuServiceImpl implements IMenuService{

    @Autowired
    private IMenuDao dao ;

    public int insert(MenuModel menu) {

        return dao.insert(menu);
    }

    /**
     * 根据父id获取子菜单
     *
     * @param pid
     * @return
     */
    public List<MenuModel> getchildByPid(int pid) {

        return dao.getchildByPid( pid);
    }

    /**
     * 根据id获取菜单
     *
     * @param id
     * @return
     */
    public MenuModel getMenuById(int id) {
        return dao.getMenuById( id);
    }

    /**
     * 获取全部菜单项
     *
     * @param id
     * @return
     */
    public List<MenuModel> getAllMenus(int id) {

        //获取一级菜单
        List<MenuModel> menus = getchildByPid(id);
        for (MenuModel model: menus) {

            setChildMenus(model);
        }
        return menus;
    }

    /**
     * 设置子菜单
     * @param parent
     */
    private void setChildMenus(MenuModel parent) {

        //
        List<MenuModel> menus = getParentAndChildMenus(parent.getId());
        if (menus.size() > 1) {//有子菜单

            List<MenuModel> childMenus = new ArrayList<MenuModel>();
            for (int i = 1; i < menus.size(); i++) {

                MenuModel child = menus.get(i);
                childMenus.add(child);
                parent.setChildMenus(childMenus);

                //递归设置子菜单
                setChildMenus(child);
            }
        }
    }

    /**
     * 根据id获取父菜单和子菜单
     * @param id
     * @return
     */
    public List<MenuModel> getParentAndChildMenus(int id) {

        return dao.getParentAndChildMenus( id) ;
    }

    /**
     * 根据菜单列表
     * @return
     */
    public List<MenuModel> getMenusList() {

        return dao.getMenusList() ;
    }

    /**
     * @param menu
     * @return
     */
    public boolean edit(MenuModel menu) {
        return dao.edit(menu);
    }
}
